package logic;

import gui.Block;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;

public class ManagerFile {

	private Document _ArchivoXML;
    private Element _Raiz;
    
    // formato
    private final String FORMAT_XML		= ".xml";
    // etiquetas
    private final String LABEL_FILE		= "file";
    private final String LABEL_CONFIG	= "config";
    private final String LABEL_CODE		= "code";
    private final String LABEL_FUNCTION	= "function";
    private final String LABEL_MAIN		= "main";
    private final String LABEL_SENT		= "sentence";
    // atributos
    private final String ATTRIB_NAME	= "name";
    private final String ATTRIB_COLOR 	= "color";
    private final String ATTRIB_TYPE 	= "type";
    private final String ATTRIB_ID 		= "id";
    private final String ATTRIB_ROW		= "row";
    private final String ATTRIB_COL 	= "col";
	 
			
	public void saveFile( ArrayList<Pestana> pPestannas, String pName ){
		// crear raiz
		_Raiz = new Element(LABEL_FILE);
		Attribute attribute = new Attribute(ATTRIB_NAME, pName);
		_Raiz.setAttribute(attribute);
		_ArchivoXML = new Document(_Raiz);
        // crear hijo config
		Element element = new Element(LABEL_CONFIG);
		_Raiz.addContent(element);
		// crear hijo code 
		Element code = new Element(LABEL_CODE);
		_Raiz.addContent(code);
		// crear pestannas
		Element pestannaXml;
		for( int cntPestannas=0; cntPestannas<pPestannas.size(); cntPestannas++ ){
			Pestana pestanna 	=	pPestannas.get(cntPestannas);
			if( cntPestannas != 0 ){
				pestannaXml = new Element(LABEL_FUNCTION);
				pestannaXml.setAttribute( new Attribute( ATTRIB_COLOR, pestanna.getId() ) );
			}else{
				pestannaXml = new Element(LABEL_MAIN);
			}
			code.addContent(pestannaXml);
			// agregar codigo
			Block token;
			Element  sentence;
			for ( int cntX=0; cntX<Constantes.CASILLAS_X; cntX++){
				for(int cntY=0; cntY<Constantes.CASILLAS_Y; cntY++){
					if( pestanna.getCasillas()[cntX][cntY] != null ){
						token = pestanna.getCasillas()[cntX][cntY];
						sentence = new Element( LABEL_SENT );
						sentence.setAttribute( new Attribute( ATTRIB_TYPE, ( (Integer)token.getType()).toString() ) );
						sentence.setAttribute( new Attribute( ATTRIB_ID,   ( (Integer)token.getId()).toString()   ) );
						sentence.setAttribute( new Attribute( ATTRIB_ROW,  ( (Integer)token.getX()).toString()    ) );
						sentence.setAttribute( new Attribute( ATTRIB_COL,  ( (Integer)token.getY()).toString()    ) );
						pestannaXml.addContent(sentence);
					}
				}			
			}
		}
		// generar archivo XML
		XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
        File nuevoXML = new File(pName+FORMAT_XML);
        try{
            FileOutputStream file = new FileOutputStream(nuevoXML);
            out.output(_ArchivoXML, file);
        } catch (Exception FileOutputException){}
	}
	    
	
	public void openFile( String pName, ArrayList<Pestana> pPestannas,  ArrayList<Integer> pConfig ){
		 try {
	            SAXBuilder builder=new SAXBuilder(false);
	            _ArchivoXML=builder.build( pName );
		 }catch (Exception JDOMException){}
		 _Raiz=_ArchivoXML.getRootElement();
		 Element code = _Raiz.getChild(LABEL_CODE);
		 // pestannas
		 List pestannasXml = code.getChildren();
		 for(int contadorPestannas=0; contadorPestannas<pestannasXml.size(); contadorPestannas++){
            //Obtener informacion del XML
            Element pestannaXml = (Element)pestannasXml.get(contadorPestannas);
            Pestana pestanna = new Pestana();
            if( pestannaXml.getName() != LABEL_MAIN ){
            	pestanna.setId( pestannaXml.getAttributeValue( ATTRIB_COLOR ) );
            }else{
            	pestanna.setId( LABEL_MAIN );
            }
            List sentences = pestannaXml.getChildren();
	   		for(int contadorSentences=0; contadorSentences<pestannasXml.size(); contadorSentences++){
	               //Obtener informacion del XML
	               Element sentence = (Element)sentences.get(contadorSentences);
	               Block bloque = new Block();
	               bloque.setType( Integer.parseInt( sentence.getAttributeValue(ATTRIB_TYPE) ) );
	               bloque.setId( Integer.parseInt( sentence.getAttributeValue(ATTRIB_ID)   ) );
	               int posX = Integer.parseInt( sentence.getAttributeValue(ATTRIB_ROW) );
	               int posY = Integer.parseInt( sentence.getAttributeValue(ATTRIB_COL) );
	               pestanna.getCasillas()[posX][posY] = bloque; 
	           } 
        }
		 
	}

}


/* Ejemplo de XML
<?xml version="1.0" encoding="UTF-8"?>
<file name="filename">
	<config>
		<pin color="rojo"  status="#" />
		<pin color="verde" status="#" />
		<pin color="azul"  status="#" />		
	</config>
	<code>
		<main>
			<sentence class=# id=## col=X row=Y />
		</main>
		<function color=FFFFFF>
			<sentence class=# id=## col=X row=Y />
			<sentence class=# id=## col=X row=Y />
			<sentence class=# id=## col=X row=Y />
		</function>
		<function color=F0F3F4>
					<sentence class=# id=## col=X row=Y />
					<sentence class=# id=## col=X row=Y />
					<sentence class=# id=## col=X row=Y />
		</function>
	</code>
</file>


*/